#include <regex>
#include <iostream>
#include <openssl/aes.h>
#include <boost/regex.hpp>
#include <memory>
//匹配模式
int test(int argc, char* argv[])
{
  //regex_match 全文完全匹配
  if(0)
  {std::string  str =R"(        
        "ratio": "cpp",
        "source_location": "cpp",
        "string_view": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "utility": "cpp",
        "format": "cpp",
        "future": "cpp",
        "initializer_list": "cpp",
        "iomanip": "cpp",
        "iosfwd": "cpp",
        "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        )"; 
  boost::regex regex1 (R"(\s*(\s*"\w*"\s*:\s*"\w*"\s*,\s*)*)");
  boost::smatch match1;
  boost::regex_match(str,match1,regex1);
  for (size_t i = 0; i < match1.size(); i++)
  {
    std::cout<<match1[i]<<std::endl;
  }
  }
  //regex_search 部分匹配
  if(0)
  {
  std::string  str =R"(        
        "ratio": "cpp",
        "source_location": "cpp",
        "string_view": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "utility": "cpp",
        "format": "cpp",
        "future": "cpp",
        "initializer_list": "cpp",
        "iomanip": "cpp",
        "iosfwd": "cpp",
        "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        )"; 
  boost::regex regex1 (R"(\s*"\w*"\s*:\s*"\w*"\s*)");
  boost::smatch match1;
  boost::regex_search(str,match1,regex1);
  for (size_t i = 0; i < match1.size(); i++)
  {
    std::cout<<match1[i]<<std::endl;
  }
  }

  //用迭代器匹配
  if(0)
  {
  std::string  str =R"(        
        "ratio": "cpp",
        "source_location": "cpp",
        "string_view": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "utility": "cpp",
        "format": "cpp",
        "future": "cpp",
        "initializer_list": "cpp",
        "iomanip": "cpp",
        "iosfwd": "cpp",
        "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        )"; 
  boost::regex regex1 (R"(\s*"\w*"\s*:\s*"\w*"\s*)");
  boost::regex_iterator it(str.begin(),str.end(),regex1);
  
  for (; it!=boost::regex_iterator<std::string::iterator, char, boost::regex_traits<char>>(); it++)
  {
      std::cout<<*it<<std::endl;
  }
  }
  
  //token迭代器 可以指定返回部匹配的部分
  if(0)
  {
  std::string  str =R"(        
   dasdas     "ratio": "cpp",
        "source_location": "cpp",
     ddd   "string_view": "cpp",
        "system_error": "cpp",
        "tuple": "cpp",
        "type_traits": "cpp",
        "utility": "cpp",
        "format": "cpp",
        "future": "cpp",
        "initializer_list": "cpp",
    1e12ess    "iomanip": "cpp",
        "iosfwd": "cpp",
   ddd     "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        )"; 
  boost::regex regex1 (R"(\s*"\w*"\s*:\s*"\w*"\s*)");
  boost::regex_token_iterator it(str.begin(),str.end(),regex1,-1);
  
  for (; it!=boost::regex_token_iterator<std::string::iterator, char, boost::regex_traits<char>>(); it++)
  {
      std::cout<<*it<<std::endl;
  }
  }
//下面的项目
if(1)
{
      std::string str=",\"content\":\"Hello! How can I assist you today?\"},";
      boost::regex reg
            (
            "\"content\"\\s*:\\s*\"(.*)\""
            );
      boost::smatch match;
      boost::regex_search(str,match,reg);
      std::cout<<match[1]<<std::endl;
}

  return 0;
}

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/json.hpp>
#include <iostream>
#include <string>
#include <sstream>

using boost::asio::ip::tcp;
namespace json = boost::json;
namespace ssl = boost::asio::ssl;

class DeepSeekClient {
public:
    DeepSeekClient() : io_context_(), ssl_context_(ssl::context::sslv23), resolver_(io_context_){
        ssl_context_.set_default_verify_paths();
    }

    // 初始化函数，配置API参数
    void init(const std::string& api_host, const std::string& api_path, const std::string& api_key) {
        api_host_ = api_host;
        api_path_ = api_path;
        api_key_ = api_key;
       try {
      // 解析API主机
      tcp::resolver::results_type endpoints = resolver_.resolve(api_host_, "443");

      // 创建SSL套接字
      this->socket_.reset(new ssl::stream<tcp::socket>(io_context_, ssl_context_));

      // 连接到API主机
      boost::asio::connect(socket_->lowest_layer(), endpoints);
      this->socket_.get()->handshake(ssl::stream_base::client);
      } catch (std::exception& e) {
            std::cerr << "connect failed: " << e.what() << std::endl;
      }
    }

    // 发送客户对话
    void send(const std::string user_input) {
        try {


            // 构建HTTP请求
            std::string request = "POST " + api_path_ + " HTTP/1.1\r\n";
            request += "Host: " + api_host_ + "\r\n";
            request += "Authorization: Bearer " + api_key_ + "\r\n";
            request += "Content-Type: application/json\r\n";
            request += "Content-Length: " + std::to_string(user_input.length()) + "\r\n";
            request += "\r\n";
            request += user_input;

            // 发送HTTP请求
            boost::asio::write(*socket_, boost::asio::buffer(request));
        } catch (std::exception& e) {
            std::cerr << "Exception in send: " << e.what() << std::endl;
        }
    }

    // 接收DeepSeek API的回复
    std::string recv() {
        try {
            boost::asio::streambuf response;
            boost::asio::read_until(*socket_, response, "\r\n");

            // 读取HTTP响应行
            std::istream response_stream(&response);
            std::string http_version;
            response_stream >> http_version;
            unsigned int status_code;
            response_stream >> status_code;
            std::string status_message;
            std::getline(response_stream, status_message);

            if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
                std::cerr << "Invalid response" << std::endl;
                return "";
            }

            // 处理301重定向
            if (status_code == 301) {
                std::string location;
                std::string header;
                while (std::getline(response_stream, header) && header != "\r") {
                    if (header.substr(0, 9) == "Location:") {
                        location = header.substr(10);
                        break;
                    }
                }
                if (!location.empty()) {
                    std::cerr << "Redirecting to: " << location << std::endl;
                    // 关闭当前连接
                    socket_->lowest_layer().close();
                    // 更新API路径并重新发送请求
                    api_path_ = location;
                    send(user_input_);
                    return recv();
                } else {
                    std::cerr << "301 response without Location header" << std::endl;
                    return "";
                }
            }

            // 处理404错误
            if (status_code == 404) {
                std::cerr << "Resource not found. Please check the URL path." << std::endl;
                return "";
            }

            if (status_code != 200) {
                std::cerr << "Response returned with status code " << status_code << std::endl;
                return "";
            }

            // 读取HTTP头
            boost::asio::read_until(*socket_, response, "\r\n\r\n");

            // 读取HTTP响应体
            char header[1028];
            response_stream.read(header,1028);

            boost::asio::read_until(*socket_, response,"\r\n");
            std::string response_body;
            std::ostringstream response_body_stream;
            response_body_stream << &response;
            response_body = response_body_stream.str();

            boost::regex reg
            (
            "\"content\"\\s*:\\s*\"(.*)\""
            );
            boost::smatch match;
            boost::regex_search(response_body,match,reg);
            return match[1];
       
        } catch (std::exception& e) {
            std::cerr << "Exception in recv: " << e.what() << std::endl;
            return "";
        }
    }

private:
    boost::asio::io_context io_context_;
    ssl::context ssl_context_;
    tcp::resolver resolver_;
    std::unique_ptr<ssl::stream<tcp::socket>> socket_;
    std::string api_host_;
    std::string api_path_;
    std::string api_key_;
    std::string user_input_;
};

int main() {
    try {
        DeepSeekClient client;
        client.init("api.deepseek.com", "/chat/completions", "sk-2a67a98fafe54623a2cee02f27ed9467");

        // 构建JSON请求
        std::string user_input = R"({
            "messages": [
                {
                    "content": "You are a helpful assistant",
                    "role": "system"
                },
                {
                    "content": "Hi",
                    "role": "user"
                }
            ],
            "model": "deepseek-chat",
            "stream": false
        })";
       client.send(user_input);
       std::cout<<client.recv()<<std::endl;
        // 发送用户输入
        
        while (true)
        {   
            std::string str;
            std::cin>>str;

            boost::regex reg
            (
            "\"content\"\\s*:\\s*\"(.*)\""
            );
            boost::smatch match;
            boost::regex_replace(user_input,reg,str);

            if(str=="quit")
            {
                  break;
            }
            client.send(str);
            std::cout<<client.recv();
        }
        
      
    } catch (std::exception& e) {
        std::cerr << "Exception in main: " << e.what() << std::endl;
    }
        
    return 0;
}
// curl https://api.deepseek.com/chat/completions \
//   -H "Content-Type: application/json" \
//   -H "Authorization: Bearer <sk-2a67a98fafe54623a2cee02f27ed9467>" \
//   -d '{
//         "model": "deepseek-chat",
//         "messages": [
//           {"role": "system", "content": "You are a helpful assistant."},
//           {"role": "user", "content": "Hello!"}
//         ],
//         "stream": false
//       }'